package com.zb.service.impl;

import com.zb.dao.BookMapper;
import com.zb.pojo.Book;
import com.zb.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author zhs
 * @create 2020-07-22-12:13
 */
@Service
@CacheConfig (cacheNames = "book") //作用redis的key开头内容
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;

    @Override
    @Cacheable //挂在查询方法上会缓存到redis里面
    public List<Book> findAll() {
        return bookMapper.findAll();
    }

    @Override
    @Cacheable(unless = "#result == null",key = "#p0") //p0代表去第0个参数  unless表示刨除 #result表示取返回结果
    public Book findById(Integer id) {
        return bookMapper.findById(id);
    }

    @Override
    @CachePut(key = "#p0.id")
    public Book add(Book book) {
        return bookMapper.add(book);
    }

    @Override
    public Book update(Book book) {
        bookMapper.update(book);
        return bookMapper.findById(book.getId());
    }

    @Override
    @CacheEvict(key = "#p0")
    public Integer deleteById(Integer id) {
        return bookMapper.deleteById(id);
    }
}
